package github.leavesczy.reactivehttpsamples.ui.main

import android.os.Bundle
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter4.BaseQuickAdapter
import github.leavesczy.reactivehttpsamples.R
import github.leavesczy.reactivehttpsamples.adapter.BridgeRecordAdapter
import github.leavesczy.reactivehttpsamples.base.BaseFragment
import github.leavesczy.reactivehttpsamples.core.mode.BridgeRecordData
import github.leavesczy.reactivehttpsamples.core.mode.BridgeRecordItem
import github.leavesczy.reactivehttpsamples.core.viewmodel.main.HistoryViewModel
import github.leavesczy.reactivehttpsamples.databinding.FragmentHistoryBinding
import github.leavesczy.reactivehttpsamples.ui.addbridge.BridgeAddActivity
import github.leavesczy.reactivehttpsamples.ui.resultdetail.ResultDetailActivity
import github.leavesczy.reactivehttpsamples.util.Logger
import github.leavesczy.reactivehttpsamples.widget.dialog.CommonDialogContent
import github.leavesczy.reactivehttpsamples.widget.divider.ItemSpaceDecoration


class HistoryFragment : BaseFragment() {
    companion object {
        fun newInstance(): Fragment {
            val fragment = HistoryFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

    private var bind: FragmentHistoryBinding? = null

    private val mBind: FragmentHistoryBinding get() = bind!!

    private val adapter = BridgeRecordAdapter()

    private var pageNum = 1
    private val pageSize = 20

    private var clickPosition:Int?=null

    private val viewModel by getViewModel<HistoryViewModel>() {
        bridgeRecordData.observe(viewLifecycleOwner) {
            Logger.d("协成的线程，livedata监听："+Thread.currentThread())
            dealAdapterData(it)
        }

        bridgeAnalysisData.observe(viewLifecycleOwner){
            showToast("处理完成")
            clickPosition?.let {index->
                val item=  adapter.getItem(index)
                item?.let { data->
                    data.resultStatus=it.resultStatus
                    data.resultJson=it.resultJson
                    data.images=it.images
                    adapter.notifyItemChanged(index)
                 }
            }
        }
        bridgeDeleteData.observe(viewLifecycleOwner){
            showToast("删除成功")
            clickPosition?.let {index->
               adapter.removeAt(index)
            }
        }

        bridgeResetResultData.observe(viewLifecycleOwner){
            //重置分析结果
            clickPosition?.let {index->
                val item=  adapter.getItem(index)
                item?.let { data->
                    data.resultStatus=0
                    //刷新条目
                    adapter.notifyItemChanged(index)
                    //跳转下一个页面
                    toEditBridge(data)
                }
            }
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        bind = FragmentHistoryBinding.inflate(inflater, container, false)
        return mBind.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initListener()
        initRefresh()
        initRecycleView()

    }

    fun initListener(){
        mBind.fabBridgeAdd.setOnClickListener {
            ActivityUtils.startActivity(BridgeAddActivity::class.java)
        }

    }

    override fun onResume() {
        super.onResume()
        if(adapter.items.isEmpty()){
            mBind.refresh.autoRefresh()
        }
    }

    private fun initRefresh() {
        mBind.refresh.setOnRefreshListener {
            pageNum = 1;
            viewModel.requestBridgeRecordList(pageNum, pageSize)
        }

        mBind.refresh.setOnLoadMoreListener {
            viewModel.requestBridgeRecordList(pageNum, pageSize)
        }

    }

    private fun initRecycleView() {
        val layoutManager= LinearLayoutManager(requireActivity())
        mBind.rvHistory.addItemDecoration(ItemSpaceDecoration(requireActivity(),ItemSpaceDecoration.VERTICAL_LIST,10,true))
        mBind.rvHistory.layoutManager = layoutManager
        mBind.rvHistory.adapter = adapter

        //点击了分析
        adapter.addOnItemChildClickListener(R.id.tvDoAnalysis
        ) { adapter, view, position ->
            clickPosition=position
            val item = adapter.getItem(position)
            viewModel.requestBridgeAnalysis(item!!.recordId)
        }
        //点击了查看结果
        adapter.addOnItemChildClickListener(R.id.tvResultDetail
        ) { adapter, view, position ->
            val item = adapter.getItem(position)
            val  bundle=Bundle()
            bundle.putSerializable("item",item)
            ActivityUtils.startActivity(bundle, ResultDetailActivity::class.java)
        }
        //点击了编辑按钮
        adapter.addOnItemChildClickListener(R.id.tvEdit
        ) { adapter, view, position ->
            clickPosition=position
            val item = adapter.getItem(position)
            if(true==item?.isHasResult()){
                //弹框，提示重置结果
                CommonDialogContent().init(requireContext(),
                    "重置分析结果","编辑桥梁档案信息会删除目前桥梁动力特性分析结果，请确认是否继续？",
                    Pair("确定", View.OnClickListener {
                        viewModel.requireBridgeResetResult(item!!.recordId)
                    }),
                    Pair("取消", View.OnClickListener {
                        //不做处理
                    })).show("CommonDialogContent")
            }else{
                toEditBridge(item!!)
            }

        }
        //点击了删除按钮
        adapter.addOnItemChildClickListener(R.id.tvDelete
        ) { adapter, view, position ->
            clickPosition=position
            val item = adapter.getItem(position)
            //弹框提醒
            CommonDialogContent().init(requireContext(),
                "记录删除提醒","是否要删除此条桥梁记录？",
                Pair("确定", View.OnClickListener {
                    viewModel.requireBridgeDelete(item!!.recordId)
                }),
                Pair("取消", View.OnClickListener {
                    //不做处理
                })).show("CommonDialogContent")

        }
        //点击整个条目，回显信息
        adapter.setOnItemClickListener{
                adapter, view, position ->
            val item = adapter.getItem(position)
            val  bundle=Bundle()
            bundle.putSerializable("item",item)
            bundle.putBoolean("forbiddenEdit",true)
            ActivityUtils.startActivity(bundle, BridgeAddActivity::class.java)
        }

    }

    private fun toEditBridge(item:BridgeRecordItem){
        val  bundle=Bundle()
        bundle.putSerializable("item",item)
        ActivityUtils.startActivity(bundle, BridgeAddActivity::class.java)
    }

    private fun dealAdapterData(it: BridgeRecordData?) {
        Logger.d("dealAdapterData--isnull:"+(it==null))
        if (isRefresh()) {
            adapter.submitList(it?.bodyList ?: mutableListOf())
            mBind.refresh.finishRefresh()
        } else {
            adapter.addAll(it?.bodyList ?: mutableListOf())
            mBind.refresh.finishLoadMore()
        }

        //页面 增加一页
        if (it?.bodyList?.isNotEmpty() == true) {
            pageNum++
        }

        dealAdapterStatus(it?.bodyList?.size?:0,pageSize,it?.totalSize?:0)

    }
    private fun dealAdapterStatus(lastListSize: Int, pageSize: Int, totalSize: Int) {
        if (totalSize == 0) {
            //添加空布局，移除footView，后续空布局就不需要移除了，就放在里面
//            adapter.setEmptyCommonView(this, R.mipmap.icon_bg_no_classes, "还没有数据哟～")
//            adapter.removeDefaultFooterView()
        } else {
//            if (lastListSize < pageSize) {
//                adapter.addDefaultFootView(this, R.color.transparent_ac)
//
//            } else {
//                adapter.removeDefaultFooterView()
//            }
        }
        //是否可以再加载更多
        val needLoadMore = lastListSize == pageSize
        mBind.refresh.setEnableLoadMore(needLoadMore)
    }

    private fun isRefresh(): Boolean {
        return pageNum == 1
    }

    override fun onDestroyView() {
        super.onDestroyView()
        bind = null
    }




}